﻿using System.IO;
using System.Reflection;

namespace InfoPathHelpers.Resources
{
    internal class ResourceHandler
    {
        internal static void SaveResourceFile(string folderPath, string resourceName)
        {
            var SplitName = resourceName.Split('.');
            FileInfo OutputFile = new FileInfo(string.Format(@"{0}\{1}.{2}",
                folderPath, SplitName[SplitName.Length - 2], SplitName[SplitName.Length - 1]));
            using (var OutputStream = OutputFile.OpenWrite())
            {
                CopyResourceFile(resourceName, OutputStream);
            }
        }

        internal static string GetResourceString(string resourceName)
        {
            using (Stream Input = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            using(StreamReader Reader = new StreamReader(Input))
            {
                return Reader.ReadToEnd();
            }
        }

        internal static void CopyResourceFile(string resourceName, Stream outputStream)
        {
            using (Stream Input = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                byte[] Buffer = new byte[4096];
                int BytesRead;
                while ((BytesRead = Input.Read(Buffer, 0, Buffer.Length)) > 0)
                {
                    outputStream.Write(Buffer, 0, BytesRead);
                }
            }
        }
    }
}
